<?php

namespace apiend\models\forms;

use Yii;
use common\models\SmsCaptchaForm;
use apiend\models\User;

/**
 * 手机短信登录模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class SmsLoginForm extends \common\models\LoginBaseModel {

    /**
     * @var string 手机号
     */
    public $mobile;

    /**
     * @var string 手机短信验证码
     */
    public $captcha;

    /**
     * @var \common\models\app\AppToken 客户端Token信息模型
     */
    public $token = null;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['mobile', 'captcha'], 'required'],
            ['mobile', 'validateUser', 'params' => ['message' => '未找到该手机号的用户']],
            ['captcha', 'validateCaptcha'],
        ];
    }

    /**
     * 校验短信验证码
     * @param string $attribute the attribute currently being validated
     */
    public function validateCaptcha($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $captcha = Yii::$app->cache->get('captcha_' . SmsCaptchaForm::SCOPE_LOGIN . '_' . $this->mobile);
        if ($captcha == false) {
            $this->addError($attribute, $this->getAttributeLabel($attribute) . '已过期');
        } elseif ($captcha !== $this->$attribute) {
            $this->addError($attribute, $this->getAttributeLabel($attribute) . '不正确');
        }
    }

    /**
     * 设置用户信息
     * @return \apiend\models\User|null
     */
    protected function setUser() {
        return User::findByMobile($this->mobile);
    }

    /**
     * 账号登录
     * @return User
     */
    public function login() {
        if (!$this->validate()) {
            $this->dumpError('用户登录失败：手机号或短信码不正确', false);
        }
        Yii::$app->cache->delete('captcha_' . SmsCaptchaForm::SCOPE_LOGIN . '_' . $this->mobile);
        return $this->getUser()->meta;
    }

}
